<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class JPush {

	private $server;
	private $CI;
	
	public function __construct() {
		$this->CI = & get_instance();
		$this->server = config_item('JPUSH_SERVER');
	}

	public function push($audience, $label, $params=array(), $extras=array()) {
		$api = $this->server . '/push';
		
		$label_arr = explode('_', $label);
		$obj = $label_arr[1];
		$extras['notify_type'] = $label;
		$extras['notify_object'] = $obj;
		foreach ($audience as &$v) {
			$v = $obj . '_' . $v;
		}
		$this->CI->load->config('system_info');
		$alert = config_item($label);
		$lpos = mb_strpos($alert, '【');
		$rpos = mb_strpos($alert, '】');
		$title = '';
		if ($lpos !== false && $rpos !== false && $lpos < $rpos) {
			$title = mb_substr($alert, $lpos + 1, $rpos - $lpos - 1);
			$alert = mb_substr($alert, $rpos + 1);
		}
		$alert = $this->labelFactory($alert, $params);
		$data = array(
			'platform' => array('android', 'ios'),
			'audience' => array(
				'alias'=>$audience
			),
			'notification' => array(
				'android' => array(
					'alert' => $alert,
					'title' => $title,
					'extras' => $extras
				),
				'ios' => array(
					'alert' => $alert,
					'extras' => $extras
				)
			),
			'options' => array(
				'time_to_live' => 0
			)
		);
		return json_decode($this->postRequest($api, $data, $obj), true);
	}

	private function labelFactory($alert, $params=array()) {
		$matches = array();
		preg_match_all('(\{[\w]+\})', $alert, $matches);
		foreach ($matches[0] as $v) {
			$var = trim($v, '{}');
			switch($var) {
				case 'time':
					$alert = str_replace($v, date('H:i'), $alert);
					break;
				default:
					$alert = (isset($params[$var])) ? str_replace($v, $params[$var], $alert) : str_replace($v, '', $alert);
					break;
			}
		}
		return $alert;
	}
	
	public function postRequest($api, $params = array(), $obj, $timeout = 30) {
		$obj = strtoupper($obj);
		$appKey = config_item("JPUSH_{$obj}_APPKEY");
		$appSecret = config_item("JPUSH_{$obj}_APPSECRET");
		$dataJson = json_encode($params);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $api);
		// 以返回的形式接收信息
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		// 设置为POST方式
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $dataJson);
		curl_setopt($ch, CURLOPT_USERPWD, $appKey . ':' . $appSecret);
		// 不验证https证书
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			'Content-type: application/json',
			'Authorization: Basic ' . base64_encode($appKey . ':' . $appSecret)
		));
		// 发送数据
		$response = curl_exec($ch);
		// 不要忘记释放资源
		curl_close($ch);
		return $response;
	}

}
